<script setup lang="ts">
import {
  deleteMemberCartAPI,
  ReplyMessageAPI,
  ReplyMessageAPI1
} from '@/services/doctor'
import { useMemberStore } from '@/stores'
import type { CartItem } from '@/types/cart'
import { onShow } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
// 是否适配底部安全区域
defineProps<{
  safeAreaInsetBottom?: boolean,
  visible: boolean;
}>()
// 添加 replyInput 变量
const replyInput = ref('');
const selectedDoctorId = ref('');
// const selectedMessage = ref(null)
const isModalVisible = ref(false);
const openModal = () => {
  isModalVisible.value = true;
};
const closeModal = () => {
  isModalVisible.value = false;
};
const onCard = (doctorId: string) => {
  selectedDoctorId.value = doctorId;
  openModal();
};
const randomImages  = [
      // 'https://th.bing.com/th/id/OIP.h5BufVlv0s9a9fpPgIACSQHaH_?w=165&h=180&c=7&r=0&o=5&dpr=1.3&pid=1.7',
      'https://th.bing.com/th?id=OIP.nrA5WVyw-9YeM3WLreXkzQHaHi&w=247&h=252&c=8&rs=1&qlt=90&o=6&dpr=1.3&pid=3.1&rm=2',
      // 'https://th.bing.com/th/id/OIP.0f_OwqggJBjjG2KTD08WsgHaHN?w=187&h=183&c=7&r=0&o=5&dpr=1.3&pid=1.7'
];
const getRandomImage = () => {
  const randomIndex = Math.floor(Math.random() * randomImages.length);
  return randomImages[randomIndex];
};
// 发送留言的方法
const onConfirmMessage = async () => {
  try {
    // 调用发送留言的接口
    await ReplyMessageAPI1({
      userId: memberStore.profile.userId,
      doctorId: selectedDoctorId.value,
      msg: replyInput.value
    });
    // 关闭弹出框
    closeModal();
    // 清空留言输入框
    replyInput.value = '';
    // 提示留言发送成功
    uni.showToast({
      title: '留言发送成功',
      icon: 'success'
    });
  } catch (error) {
    // 处理发送留言失败的情况
    console.error('发送留言失败:', error);
    uni.showToast({
      title: '留言发送失败，请重试',
      icon: 'none'
    });
  }
};
// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
const isRefreshing = ref(false);
	const scrollViewHeight = ref('400px');
	// 刷新数据的方法
	const refreshData = async () => {
		isRefreshing.value = true;
		await getMemberCartData()

		setTimeout(() => {
			isRefreshing.value = false;
		}, 2000)
	};
	let throttleTimer = ref()
	// 下拉事件被复位
	const onRestore = (e) => {
		isRefreshing.value = false;
		console.log("onRestore", e);
	}
	const onPulling = (e : any) => {
		if (!throttleTimer.value) {
			// 如果节流定时器不存在，则执行点击逻辑，并设置定时器
			console.log('Button clicked');
			throttleTimer.value = setTimeout(() => {
				// 1秒后清除定时器，允许下一次点击
				throttleTimer.value = null;
				// refreshData()
			}, 1000); // 设置节流时间间隔为1秒
		} else {
			// 如果节流定时器存在，则表示函数已经在节流中，不执行点击逻辑
			console.log('Function is throttled');
		}
		console.log("onpulling", e);
	}
// 获取Store
const memberStore = useMemberStore()

// 获取数据
const cartList = ref<CartItem[]>([])
const getMemberCartData = async () => {
  try {
    if (!memberStore.profile) {
      console.error('用户未登录');
      return;
    }
    // 使用当前用户的 userId 进行 API 调用
    const res = await ReplyMessageAPI(memberStore.profile.userId);
    console.log('已回复列表', res);
    cartList.value = res.data.userDoctorVOList
  } catch (error) {
    // 处理异常情况
    console.error('获取回复消息列表失败:', error);
  }
};
// 初始化调用: 页面显示触发
onShow(() => {
  if (memberStore.profile) {
    getMemberCartData()
  }
})
// 点击删除按钮
const onDeleteCart = (skuId: string) => {
  // 弹窗二次确认
  uni.showModal({
    content: '是否删除',
    success: async (res) => {
      if (res.confirm) {
        // 后端删除
        await deleteMemberCartAPI({ ids: [skuId] })
        // 重新获取列表
        getMemberCartData()
      }
    },
  })
}
</script>

<template>
  <scroll-view enable-back-to-top scroll-y class="scroll-view" :refresher-threshold="100" refresher-background="white" :refresher-enabled="true" style="height:1000px"
		@refresherpulling="onPulling" @refresherrefresh="refreshData()" @refresherrestore="onRestore"
		:refresher-triggered="isRefreshing">
    <!-- 已登录: 显示留言信息 -->
    <template v-if="memberStore.profile">
      <!-- 留言列表 -->
      <view class="cart-list" v-if="cartList.length">
        <!-- 滑动操作分区 -->
        <uni-swipe-action>
          <!-- 滑动操作项 -->
          <uni-swipe-action-item v-for="item in cartList" :key="item.doctorId" class="cart-swipe">
            <!-- 信息 -->
            <view class="goods" @click="onCard(item.doctorId)">
                <image mode="aspectFill" class="picture" :src="getRandomImage()"></image>
                <view class="meta">
                  <!-- <view class="name ellipsis">医生编号：{{ item.doctorId }}</view> -->
                  <view class="name ellipsis">
                   医生姓名： {{item.doctorName}}
                  </view>
                  <view class="name ellipsis">
                   所属医院： {{item.doctorHospital}}
                  </view>
                  <view class="price">{{ item.doctorDepartment }}</view>
                </view>
            </view>
            <!-- 右侧删除按钮 -->
            <template #right>
              <view class="cart-swipe-right">
                <button @tap="onDeleteCart(item.messageId)" class="button delete-button">删除</button>
              </view>
            </template>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </view>
      <!-- 留言空状态 -->
      <view class="cart-blank" v-else>
        <button>暂无</button>
      </view>
    </template>
    <!-- 未登录: 提示登录 -->
    <view class="login-blank" v-else>
      <text class="text">登录后可查看留言信息</text>
      <navigator url="/pages/login/login" hover-class="none">
        <button class="button">去登录</button>
      </navigator>
    </view>
    <!-- 底部占位空盒子 -->
    <!-- <view class="toolbar-height"></view> -->
      <view v-if="isModalVisible" class="modal">
        <view class="modal-content">
          <textarea v-model="replyInput" placeholder="请输入留言信息"></textarea>
          <view class="modal-buttons">
            <button @click="onConfirmMessage" class="confirm-button">确定</button>
            <button @click="closeModal" class="cancel-button">取消</button>
          </view>
        </view>
        </view>
  </scroll-view>

</template>

<style lang="scss">
  .popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    .popup-content {
      background-color: #fff;
      padding: 20px;
      border-radius: 40px;
      width: 400px;
      height: 500px;
    }
    .popup-content {
        position: relative;
        .close-button {
          position: absolute;
          top: -20px;
          right: 7px;
          font-size: 40px;
          color: #333;
          background: none;
          border: none;
          cursor: pointer;
        }
        .huifu{
          position: absolute;
          background-color: #A5DD9B;
          width: 50%;
          bottom: 20px; /* 距离底部的距离 */
          left: 50%; /* 居中 */
          transform: translateX(-50%); /* 使按钮居中 */
        }
        }
  }
// 根元素
:host {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f7f7f8;
}

// 滚动容器
.scroll-view {
  flex: 1;
}

// 购物车列表
.cart-list {
  padding: 0 20rpx;

  // 优惠提示
  .tips {
    display: flex;
    align-items: center;
    line-height: 1;
    margin: 30rpx 10rpx;
    font-size: 26rpx;
    color: #666;

    .label {
      color: #fff;
      padding: 7rpx 15rpx 5rpx;
      border-radius: 4rpx;
      font-size: 24rpx;
      background-color: #626dba;
      margin-right: 10rpx;
    }
  }


  .goods {
    display: flex;
    padding: 20rpx 20rpx 20rpx 80rpx;
    border-radius: 10rpx;
    background-color: white;
    position: relative;
    border-radius: 40rpx;
    .navigator {
      display: flex;
    }

    .checkbox {
      position: absolute;
      top: 0;
      left: 0;

      display: flex;
      align-items: center;
      justify-content: center;
      width: 80rpx;
      height: 100%;

      &::before {
        content: '\e6cd';
        font-family: 'erabbit' !important;
        font-size: 40rpx;
        color: #444;
      }

      &.checked::before {
        content: '\e6cc';
        color: #27ba9b;
      }
    }

    .picture {
      width: 170rpx;
      height: 170rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin-left: 20rpx;
    }

    .name {
      height: 72rpx;
      font-size: 26rpx;
      color: #444;
      margin-bottom: -10rpx;
    }

    .attrsText {
      line-height: 1;
      padding: 0 5rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      // background-color: #f7f7f8;
    }

    .price {
      line-height: 1;
      font-size: 26rpx;
      color: #444;
      margin-bottom: 2rpx;
      color: #cf4444;

      &::before {
        content: '所属科室：';
        font-size: 80%;
      }
    }

    // 商品数量
    .count {
      position: absolute;
      bottom: 20rpx;
      right: 5rpx;

      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 220rpx;
      height: 48rpx;

      .text {
        height: 100%;
        padding: 0 20rpx;
        font-size: 32rpx;
        color: #444;
      }

      .input {
        height: 100%;
        text-align: center;
        border-radius: 4rpx;
        font-size: 24rpx;
        color: #444;
        background-color: #f6f6f6;
      }
    }
  }

  .cart-swipe {
    display: block;
    margin: 20rpx 0;
  }

  .cart-swipe-right {
    display: flex;
    height: 100%;

    .button {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 50px;
      padding: 6px;
      line-height: 1.5;
      color: #A5DD9B;
      font-size: 26rpx;
      border-radius: 0;
    }

    .delete-button {
      background-color: #cf4444;
    }
  }
}

// 空状态
.cart-blank,
.login-blank {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  height: 60vh;
  button{
    display: flex;
          justify-content: center;
          align-items: center;
          width: 100px;
          padding: 6px;
          line-height: 1.5;
          background-color: #A5DD9B;
          font-size: 28rpx;
          border-radius: 20rpx;
          color: white;
  }
  .image {
    width: 400rpx;
    height: 281rpx;
  }
  .text {
    color: #444;
    font-size: 26rpx;
    margin: 20rpx 0;
  }
  .button {
    width: 240rpx !important;
    height: 60rpx;
    line-height: 60rpx;
    margin-top: 20rpx;
    font-size: 26rpx;
    border-radius: 60rpx;
    color: #fff;
    background-color: #A5DD9B;
  }
}

// 吸底工具栏
.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;
.button {
  border-radius: 40rpx;
  background-color: #A5DD9B;
}

  .all {
    margin-left: 25rpx;
    font-size: 14px;
    color: #444;
    display: flex;
    align-items: center;
  }

  .all::before {
    font-family: 'erabbit' !important;
    content: '\e6cd';
    font-size: 40rpx;
    margin-right: 8rpx;
  }

  .checked::before {
    content: '\e6cc';
    color: #27ba9b;
  }

  .text {
    margin-right: 8rpx;
    margin-left: 32rpx;
    color: #444;
    font-size: 14px;
  }

  .amount {
    font-size: 20px;
    color: #cf4444;

    .decimal {
      font-size: 12px;
    }

    &::before {
      content: '￥';
      font-size: 12px;
    }
  }

  .button-grounp {
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    text-align: center;
    line-height: 72rpx;
    font-size: 13px;
    color: #fff;

    .button {
      width: 240rpx;
      margin: 0 10rpx;
      border-radius: 72rpx;
    }

    .payment-button {
      background-color: #27ba9b;

      &.disabled {
        opacity: 0.6;
      }
    }
  }
}

// 底部占位空盒子
.toolbar-height {
  height: 100rpx;
}
.modal-wrapper {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.5);
}

.modal {
  position: absolute;
  top: 35%;
  left: 17%;
  background-color: white;
  padding: 20px;
  border-radius: 40px;
  width: 300px;
  height: auto;
  transition: transform 0.3s ease-out; // 添加过渡动画
}

.modal-buttons {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
.confirm-button{
  margin-right: 10px;
  background-color: #A5DD9B;
  width: 200px;
  border-radius: 20px;
}
.cancel-button{
  width: 200px;
  border-radius: 20px;
}
</style>
